package com.fmx.BookStore.controller;

import com.fmx.BookStore.core.domain.AjaxResult;
import com.fmx.BookStore.domain.Book;
import com.fmx.BookStore.service.IBookService;
import com.fmx.BookStore.service.ISaleService;
import com.fmx.BookStore.vo.SaleItemVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/sale")
public class SaleController {
    @Autowired
    private ISaleService saleService;

    @Autowired
    private IBookService bookService;

    /**
     * 开始一次新的销售
     */
    @GetMapping("/makeNewSale")
    public AjaxResult makeNewSale(){
        return AjaxResult.success(saleService.makeNewSale());
    }

    /**
     * 输入商品
     * @param bookId 书本Id
     * @param quantity 数量
     */
    @GetMapping("/enterItem")
    public AjaxResult enterItem(@RequestParam("bookId") Long bookId, @RequestParam("quantity") int quantity){
        SaleItemVo saleItemVo = null;
        Book book = bookService.getBookById(bookId);
        if( book != null ){
            saleService.makeLineItem(book,quantity);
            saleItemVo = new SaleItemVo(bookId,book.getBookName(),book.getPrice(),quantity);
            return AjaxResult.success(saleItemVo);
        }
        else {
            return AjaxResult.error("未找到商品");
        }
    }

    /**
     * 结束销售
     */
    @GetMapping("/endSale")
    public AjaxResult endSale(){
        return AjaxResult.success(saleService.endSale());
    }

    /**
     * 确认支付
     * @param cashTendered 支付金额
     */
    @GetMapping("/makePayment")
    public AjaxResult makePayment(@RequestParam("cashTendered") BigDecimal cashTendered){
        return AjaxResult.success(saleService.makePayment(cashTendered));
    }

    /**
     * 删除商品明细
     */
    @GetMapping("/deleteSaleItem/{bookId}")
    @ApiOperation("删除一行订单明细")
    public AjaxResult deleteSaleItem(@PathVariable("bookId") Long bookId){
        saleService.deleteSaleItem(bookId);
        return AjaxResult.success("删除订单明细成功");
    }

    @PostMapping("/changeNum")
    @ApiOperation("修改一行订单明细数量")
    public AjaxResult changeNum(@RequestBody SaleItemVo saleItemVo){
        saleService.changeNum(saleItemVo.getBookId(),saleItemVo.getQuantity());
        return AjaxResult.success("修改订单明细数量成功");
    }
}
